package main

import (
	"math/rand"
	"github.com/afex/hystrix-go/hystrix"
	"time"
	"fmt"
)

type Product struct {
	Id int
	Title string
	Price int
}

func getProduct()(Product, error){
	r := rand.Intn(10)
	if r < 6{
		time.Sleep(time.Second*3)
	}
	return Product{
		Id : 101,
		Title: "Golang",
		Price: 79,
	}, nil
	
}

func main(){

	rand.Seed(time.Now().UnixNano())
	configA := hystrix.CommandConfig{
		Timeout: 1000,
	}
	hystrix.ConfigureCommand("getProduct", configA)

	//同步
	// for{
	// 	err := hystrix.Do("getProduct", func() error{
	// 		p, _:= getProduct()
	// 		fmt.Println(p)
	// 		return nil
	// 	}, func (e error) error{
	// 		var oldPro = Product{
	// 			Id : 120,
	// 			Title: "php",
	// 			Price: 39,
	// 		}
	// 		fmt.Println(oldPro)
	// 		return nil
	// 	})

	// 	if err != nil{
	// 		fmt.Println(err)
	// 	}
	// 	time.Sleep(time.Second*1)

	// }

	//异步
	resultChan := make(chan Product, 1)
	hystrix.ConfigureCommand("getProduct", configA)
	for{
		errs := hystrix.Go("getProduct", func() error{
			p, _:= getProduct()
			resultChan <- p
			return nil
		}, func (e error) error{
			var oldPro = Product{
				Id : 120,
				Title: "php",
				Price: 39,
			}
			resultChan <- oldPro
			return nil
		})

		select{
		case getPro := <- resultChan:
			fmt.Println(getPro)
		case err := <- errs:
			fmt.Println(err)
		}

		time.Sleep(time.Second*1)

	}
}